package top.mypath.page;

import cn.hutool.core.util.ObjectUtil;
import com.sun.deploy.panel.NumberDocument;
import lombok.SneakyThrows;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang.StringUtils;
import top.mypath.model.dto.CacheData;
import top.mypath.model.dto.HeadSelectItem;
import top.mypath.model.dto.SheetSelectItem;
import top.mypath.util.DoubleDocument;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.event.*;
import java.io.File;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

public class FirstPage extends JPanel {

    private JTextField filePathField;

    private JComboBox<SheetSelectItem> sheetJComboBox;

    private JTextField headTextField;

    private JComboBox<HeadSelectItem> totalJComboBox;

    private JTextField invoiceField;

    private JTextField taxRateField;

    private JRadioButton maxRadioButton;

    private JRadioButton sequenceButton;

    private ButtonGroup radioGroup;


    public FirstPage() throws NoSuchFieldException, IllegalAccessException {
        MigLayout migLayout = new MigLayout("wrap 4","[grow,right,25%][grow,fill,25%][grow,25%][grow,fill,25%]","25%");
        this.setLayout(migLayout);
        cretePanelLayout();
    }

    private void cretePanelLayout() {
        JLabel fileLabel = new JLabel("选择数据文件：");
        JLabel sheetLabel = new JLabel("选择Sheet表：");
        JLabel titleLabel = new JLabel("表头所在行：");
        JLabel totalLabel = new JLabel("请选择金额列：");
        JLabel invoiceLabel = new JLabel("发票限额：");
        JLabel taxRateLabel = new JLabel("税率：");
        JLabel excreteLabel = new JLabel("拆分方式：");
        filePathField = new JTextField();
        sheetJComboBox = new JComboBox<>();
        headTextField = new JTextField();
        totalJComboBox = new JComboBox<>();
        invoiceField = new JTextField();
        taxRateField = new JTextField();
        invoiceField.setDocument(new DoubleDocument());
        taxRateField.setDocument(new DoubleDocument());
        maxRadioButton = new JRadioButton("最大值拆分",Boolean.TRUE);
        sequenceButton = new JRadioButton("顺序拆分");
        radioGroup = new ButtonGroup();
        radioGroup.add(maxRadioButton);
        radioGroup.add(sequenceButton);
        this.add(fileLabel);
        this.add(filePathField,"span 3");
        filePathField.setText("点击选择文件");
        filePathField.setEnabled(Boolean.FALSE);
        this.add(sheetLabel);
        this.add(sheetJComboBox,"span 3");
        this.add(titleLabel);
        this.add(headTextField);
        headTextField.setDocument(new NumberDocument());
        this.add(totalLabel,"align right");
        this.add(totalJComboBox);
        this.add(invoiceLabel);
        this.add(invoiceField);
        invoiceField.setText("113000");
        this.add(taxRateLabel,"align right");
        this.add(taxRateField);
        taxRateField.setText("0.13");
        this.add(excreteLabel);
        this.add(maxRadioButton);
        this.add(sequenceButton,"span 2");
        filePathField.addMouseListener(new MouseListener() {
            @SneakyThrows
            @Override
            public void mouseClicked(MouseEvent e) {
                int clickCount = e.getClickCount();
                if (clickCount == 1) {
                    JFileChooser fileChooser = new JFileChooser();
                    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    fileChooser.setFileFilter(new FileNameExtensionFilter("只能选择Excel文件","xls","xlsx"));
                    int option = fileChooser.showOpenDialog(MainPage.getFrame());
                    if (option == JFileChooser.APPROVE_OPTION) {
                        File file = fileChooser.getSelectedFile();
                        CacheData.setExcelFile(file);
                        CacheData.setFilePath(file.getPath());
                        filePathField.setText(file.getPath());
                        CacheData.readFileSheet();
                        List<SheetSelectItem> sheetSelectItems = CacheData.getSheetSelectItems();
                        sheetJComboBox.removeAllItems();
                        for (SheetSelectItem sheetSelectItem : sheetSelectItems) {
                            sheetJComboBox.addItem(sheetSelectItem);
                        }
                    }
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        });
        sheetJComboBox.addActionListener(sheetJComboBoxListener(sheetJComboBox));
        headTextField.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {

            }

            @Override
            public void focusLost(FocusEvent e) {
                if(!ObjectUtil.isEmpty(CacheData.getExcelFile())){
                    if(CacheData.getShowCheckBoxItems()!=null&&!Objects.equals(Integer.valueOf(headTextField.getText()), CacheData.getHeadRow())) {
                        CacheData.getShowCheckBoxItems().clear();
                    }
                    CacheData.setHeadRow(Integer.valueOf(headTextField.getText()));
                    CacheData.readSheet();
                    List<HeadSelectItem> headSelectItems = CacheData.getHeadSelectItems();
                    totalJComboBox.removeAllItems();
                    for (HeadSelectItem headSelectItem : headSelectItems) {
                        totalJComboBox.addItem(headSelectItem);
                    }
                }
            }
        });
        totalJComboBox.addActionListener(e -> {
            HeadSelectItem selectedItem = (HeadSelectItem) totalJComboBox.getSelectedItem();
            CacheData.setHeadSelectItem(selectedItem);
        });
        doubleInputSupplementZero(invoiceField);
        doubleInputSupplementZero(taxRateField);
    }

    private void doubleInputSupplementZero(JTextField invoiceField) {
        invoiceField.addFocusListener(new FocusListener() {

            @Override
            public void focusGained(FocusEvent e) {

            }

            @Override
            public void focusLost(FocusEvent e) {
                String text = invoiceField.getText();
                if(StringUtils.isEmpty(text)){
                    return;
                }
                if(text.endsWith(".")){
                    text=text+"0";
                }
                invoiceField.setText(text);
            }
        });
    }


    private ActionListener sheetJComboBoxListener(JComboBox comboBox){
        return e -> {
            SheetSelectItem selectedItem = (SheetSelectItem) comboBox.getSelectedItem();
            if (selectedItem != null) {
                if(CacheData.getShowCheckBoxItems()!=null&&!selectedItem.equals(CacheData.getSelectSheetItem())){
                    CacheData.getShowCheckBoxItems().clear();
                }
                CacheData.setSelectSheetItem(selectedItem);
            }
        };
    }

    public void setLimitMoneyAndTaxRate(){
        String invoiceFieldText = invoiceField.getText();
        if(StringUtils.isNotBlank(invoiceFieldText)){
            BigDecimal limitMoney = BigDecimal.valueOf(Double.parseDouble(invoiceFieldText));
            CacheData.setLimitMoney(limitMoney);
        }
        String taxRateFieldText = taxRateField.getText();
        if(StringUtils.isNotBlank(taxRateFieldText)){
            CacheData.setTaxRate(taxRateFieldText);
        }
    }



    public void setSplitManner(){
        if(maxRadioButton.isSelected()){
            CacheData.setSplitManner("cupidity");
        }else{
            CacheData.setSplitManner("order");
        }
    }
}
